package com.wondream.myframework.app.common.util;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

/**
 * RSA加解密
 */
public class RSAUtils {

    public static final String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQDQIWYTzLFcOHRpSCgWWgvdOBhLNSrJcHq5pRmS7XwYHg6F7V+f3zsgmCtPW87dDZ2JSyvnSYkPFGCs9zk+hGq5nDzrtrZiW+c8J8fSII2VyfGa+Ytv5RM8rTpe7NeVlQzwjLXrCCYpiIxRMPnGfzqQj4RRcI8jIiBDt58Akm+2ee0Ygeo35Ic/aNnK7YdTHI4cfKD1YuBCNFKEt9mw+IjjBHsmJ1ojyCm7UMBTQyqY75lkYCcFB2Zr+aHZTdlsRYtnXuCGKvKqn+KMNNZwMN5MNdVRPtIjtGTiyYmpdxjT684uF39J/pRTJSVW0su4Q02yZMrAm9MMUj3Ro52PqA9PAgMBAAECggEAHCmoyl0UUspA1k4xPnUIzfJdNzAGjiNuN9ijUUJZXFoU1QJ9wgBO2+Y7Vg2yPC8vdfh6BF3q8eNsAXuif1cjqeH+TFb47u5Ip9cqLsDA59ffnXzO5WE17Svzjgy2T0NP8OzZYOhFYbFca1AZPEbTAeSpnuuAMtzXSNJ77XPjMemnNcmaRMz7v/AG6zyA1n/PLA9AgO1EiynFHtkLpToAl/YH5ljNovEpb1K4MQzKgC/xjDJeB9+H3UxYjc2XkWin88XhOgFaVV1cQgMPiFtTRBGb7Qv1YWdGWbyQ3fzupwYJyV8c/4r3nxrHAD7DqkKXc0wG6TceD4etaOOHrdgjoQKBgQDqMbH4o0MLIrcs/OCydsWuQPLTSmSWNrlMePA036KKcvhjQB4NsYj94qHaYZh0RbQqwEkkow6efLRPVCZ7ZPFAmpnqM7HNKEL+aDrJEtuAtgCLNNlXSy7udZ+0fgtnxklhdpOTYyMM7hoHW0dNNcF4mCSbCffOnpFFldFc6FgudQKBgQDjgnG3qPmwZN696nkGqFvKnVg/+ruerEPvguI+6AlEs/vubvcN+87OiBRpW2kFoC5VdtPbLFkXeHHXQAo6m5aIkI5QvVNDG18JzWSWcia53ajgYMI/r2UFsno9toL/kzcDTvzd9/LDQ7fqvdUNUXtun/tNPP2k24RR8EahnB3WMwKBgQCiSfPBkCl6gwEazNZM9Z+BZIKhRtEzgxKfWsNicILrnEZiSOFKrfd3sGBmu/DwygjTA1Lsb45G57XvrynHoqjIExqLwGz69WaPc90gz8+KfxUbYnEmW/RWzO3yHtJ6hF7/ijM0FKQKZslkxa1AZPsAPbZINf0ikqGq7eoajuvkrQKBgENMQMstJr7w95qCE07O2mgy5vn19y3Wkzn0I2ysQqGaA/nhxR7Tz7b0NeV8brKFUW9ieQSqN6hjrnkXrm7ruzmmWRK1Dj4ZiKFjqk9+cMomMWA9/vfLsDxhMRu0M0faijlmUhJu19a+31aG1NDdu39bv4B3fCgZ7yg1xQ7lGUZVAoGBALZFlMsGn6Y55FIlwsHTBZc1i6wzhbCThKHIU3BNgCEOoqCya1sEDgApeYQBkbbCFIbTHI5Gxa0c/64056HYEUl5X4Udvkmgh1faz4PJaK0XDoy9LBgLz0qLREQlR2nv56D7/xqufRd42Ztuvh6w4+0aQ/E9aFfoNhIuSbX7WGt6";
    public static final String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCK8HobvWSh+WzfsW39bWaILR9/swaKIR3/HWdL0nSzuFHREMLCXb4YiYznW1MR6Be4H+zCCpxngVFli+qJ8G+5Wjnm7N1HMQkY9rEvTmoChX3VSNl6BPBKvU6gNIPRfLC9QZiQPCsN10pXdd4fW/XI3c54oAkOXGqIihJCqXoPnwIDAQAB";

    // RSA最大加密明文大小
    public static final int MAX_ENCRYPT_BLOCK = 117;

    // RSA最大解密密文大小
    public static final int MAX_DECRYPT_BLOCK = 128;

    /**
     * 获取密钥对
     */
    public static KeyPair getKeyPair() throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048);
        return generator.generateKeyPair();
    }

    /**
     * 获取私钥
     */
    public static PrivateKey getPrivateKey(String privateKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodeKey = Base64.decodeBase64(privateKey.getBytes());
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(decodeKey);
        return keyFactory.generatePrivate(keySpec);
    }

    /**
     * 获取公钥
     */
    public static PublicKey getPublicKey(String publicKey) throws Exception {
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        byte[] decodeKey = Base64.decodeBase64(publicKey.getBytes());
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(decodeKey);
        return keyFactory.generatePublic(keySpec);
    }

    /**
     * RSA加密
     */
    public static String encrypt(String data, PublicKey publicKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段加密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_ENCRYPT_BLOCK) {
                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_ENCRYPT_BLOCK;
        }
        byte[] encrytedData = out.toByteArray();
        out.close();
        // 获取加密内容使用base64进行编码，并以UTF-8为标准转化成字符串
        return new String(Base64.encodeBase64String(encrytedData));
    }

    /**
     * RSA解密
     */
    public static String decrypt(String data, PrivateKey privateKey) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] dataBytes = Base64.decodeBase64(data);
        int inputLen = data.getBytes().length;
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int offset = 0;
        byte[] cache;
        int i = 0;
        // 对数据分段解密
        while (inputLen - offset > 0) {
            if (inputLen - offset > MAX_DECRYPT_BLOCK) {
                cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);
            } else {
                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);
            }
            out.write(cache, 0, cache.length);
            i++;
            offset = i * MAX_DECRYPT_BLOCK;
        }
        byte[] decrytedData = out.toByteArray();
        out.close();
        // 获取加密内容使用base64进行编码，并以UTF-8为标准转化成字符串
        return new String(decrytedData);
    }

    /**
     * 签名
     */
    public static String sign(String data) throws Exception {
        byte[] keyBytes = getPrivateKey(privateKey).getEncoded();
        PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initSign(privateKey);
        signature.update(data.getBytes());
        return new String(Base64.encodeBase64(signature.sign()));
    }


    /**
     * 验证签名
     */
    public static boolean verify(String srcData, String sign) throws Exception {
        byte[] keyBytes = getPublicKey(publicKey).getEncoded();
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        PublicKey publicKey = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance("MD5withRSA");
        signature.initVerify(publicKey);
        signature.update(srcData.getBytes());
        return signature.verify(Base64.decodeBase64(sign.getBytes()));
    }

    public static void main(String[] args) throws Exception {
//        // 生成密钥对
//        KeyPair keyPair = getKeyPair();
//        String privateKey = new String(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));
//        String publicKey = new String(Base64.encodeBase64(keyPair.getPublic().getEncoded()));
//        System.out.println("私钥：" + privateKey);
//        System.out.println("公钥：" + publicKey);

        // RSA加密
        String data = "待加密的文字内容";
        String encryptData = encrypt(data, getPublicKey(publicKey));
        System.out.println("加密后的内容：" + encryptData);

        // RSA解密
        String decryptData = decrypt(encryptData, getPrivateKey(privateKey));
        System.out.println("解密后的内容：" + decryptData);

        // RSA签名
        String sign = sign(data);
        System.out.println("签名后的内容：" + sign);

        // RSA验签
        boolean result = verify(data, sign);
        System.out.println("验签结果：" + result);
    }


}
